package com.yonyou.crm.cum.customer.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yonyou.crm.base.doc.service.BaseDocDetailBizServiceImpl;
import com.yonyou.crm.base.industry.service.IndustryBizServiceImpl;
import com.yonyou.crm.bpub.refervalue.entity.ReferDataVO;
import com.yonyou.crm.common.biz.service.BaseBizServiceImpl;
import com.yonyou.crm.common.enumeration.service.EnumBizServiceImpl;
import com.yonyou.crm.common.exception.CrmBusinessException;
import com.yonyou.crm.common.field.handler.FieldRelationHandler;
import com.yonyou.crm.common.field.relation.EnumFieldRelation;
import com.yonyou.crm.common.field.relation.FieldRelation;
import com.yonyou.crm.common.field.relation.RefFieldRelation;
import com.yonyou.crm.common.login.context.LoginContextConstant;
import com.yonyou.crm.common.model.util.IConverter;
import com.yonyou.crm.common.model.util.ModelUtil;
import com.yonyou.crm.common.page.entity.Page;
import com.yonyou.crm.common.pub.entity.ObjTypeEnum;
import com.yonyou.crm.common.search.entity.AppSearchPlanEnum;
import com.yonyou.crm.cum.customer.dynamic.DymGCumDisable;
import com.yonyou.crm.cum.customer.dynamic.DymGCumEnable;
import com.yonyou.crm.cum.customer.dynamic.DymGCumLocationSave;
import com.yonyou.crm.cum.customer.dynamic.DymGCumLocationUpdate;
import com.yonyou.crm.cum.customer.dynamic.DymGCustomerCreate;
import com.yonyou.crm.cum.customer.dynamic.DymGCustomerUpdate;
import com.yonyou.crm.cum.customer.entity.CustomerDO;
import com.yonyou.crm.cum.customer.entity.CustomerRelusersVO;
import com.yonyou.crm.cum.customer.entity.CustomerSalesVO;
import com.yonyou.crm.cum.customer.entity.CustomerVO;
import com.yonyou.crm.cum.customer.entity.CustomerViewDO;
import com.yonyou.crm.cum.customer.entity.GroupCustomerDO;
import com.yonyou.crm.sys.dataright.service.RightServiceImpl;
import com.yonyou.crm.sys.dynamic.builder.Field;
import com.yonyou.crm.sys.dynamic.builder.Link;
import com.yonyou.crm.sys.dynamic.entity.DynamicVO;
import com.yonyou.crm.sys.dynamic.filter.BusiFilter;
import com.yonyou.crm.sys.dynamic.filter.DateTimeFilter;
import com.yonyou.crm.sys.dynamic.filter.MyFilter;
import com.yonyou.crm.sys.dynamic.impl.DynamicServiceImpl;
import com.yonyou.crm.sys.modules.service.BiztypeBizServiceImpl;
import com.yonyou.crm.sys.org.service.SysOrgBizServiceImpl;
import com.yonyou.crm.sys.queryplan.service.QueryPlanBizService;
import com.yonyou.crm.sys.region.service.RegionsBizServiceImpl;
import com.yonyou.crm.sys.role.service.RoleBizServiceImpl;
import com.yonyou.crm.sys.user.entity.UserVO;
import com.yonyou.crm.sys.user.service.UserBizServiceImpl;
import com.yonyou.iuap.context.InvocationInfoProxy;

@Service
public class GroupCustomerBizServiceImpl extends BaseBizServiceImpl<GroupCustomerDO> {
	
	@Autowired
	private CustomerViewBizServiceImpl viewService;
	@Autowired
	private EnumBizServiceImpl enumService;
	@Autowired
	private RegionsBizServiceImpl regionService;
	@Autowired
	private BaseDocDetailBizServiceImpl baseDocDetailBizService;
	@Autowired
	private IndustryBizServiceImpl IndustryBizService;
	@Autowired
	private GroupCustomerSalesBizServiceImpl saleService;
	@Autowired
	private SysOrgBizServiceImpl orgService;
	@Autowired
	private UserBizServiceImpl userService;
	@Autowired
	private RoleBizServiceImpl roleService;
	@Autowired
	private RightServiceImpl rightService;
	@Autowired
	private QueryPlanBizService queryService;
	@Autowired
	private DynamicServiceImpl dynamicService;
    @Autowired
    private BiztypeBizServiceImpl biztypeService;
    @Autowired
    private CustomerRelusersBizServiceImpl cusreluserService;
	
	public CustomerVO getDetail(Long id) {
		String tenantIdStr = (String)InvocationInfoProxy.getTenantid();
		Long tenantId = Long.parseLong(tenantIdStr);
		GroupCustomerDO groupCustomerDO = super.getVOById(GroupCustomerDO.class, id);
		CustomerVO vo = ModelUtil.copyModel(groupCustomerDO, CustomerVO.class);
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("tenantId", tenantId);
		param.put("cumId", id);
		List<CustomerSalesVO> saleVOs = saleService.selectByCustomer(param);
		if (saleVOs.size() > 0) {
			vo.setSalesVOs(saleVOs);
		}
		transCustomer(Arrays.asList(vo));
		return vo;
	}
	
	public CustomerVO viewDetail(Long id) {
		CustomerVO vo = getDetail(id);
		CustomerViewDO viewDO = new CustomerViewDO();
		viewDO.setCumId(id);
		viewService.saveVO(viewDO);
		return vo;
	}
	
	public Page<CustomerVO> getList(Page<CustomerVO> page, Map<String, Object> paramMap) {
		//PC端使用
		if (paramMap.containsKey("province_city_district")) {
			String pcdStr = (String)paramMap.get("province_city_district");
			String[] pcd = pcdStr.split("_");
			if (pcd.length != 0 && pcd.length != 3) {
				throw new CrmBusinessException("查询参数格式错误");
			}
			try {
				paramMap.put("province", Integer.parseInt(pcd[0]));
				paramMap.put("city", Integer.parseInt(pcd[1]));
				paramMap.put("district", Integer.parseInt(pcd[2]));
			} catch (Exception e) {
				throw new CrmBusinessException("查询参数格式错误");
			}
			paramMap.remove("province_city_district");
		}

		if (paramMap.containsKey("option")) {
			// 查询方案，从库中查询？
			int searchPlan = (Integer)paramMap.get("option");
			paramMap.remove("option");
			if (searchPlan == AppSearchPlanEnum.ALL.getValue()) {// 当前全部客户只有我负责的
				return getMyOwnerList(page, paramMap);
			} else if (searchPlan == AppSearchPlanEnum.OWNER.getValue()) {// 我负责的
				return getMyOwnerList(page, paramMap);
			} else if (searchPlan == AppSearchPlanEnum.REL.getValue()) {//我参与的
				return getMyRelList(page, paramMap);
			} else if (searchPlan == AppSearchPlanEnum.FOLLOW.getValue()) {//我关注的
				return getMyFollowList(page, paramMap);
			} else if (searchPlan == AppSearchPlanEnum.VIEW.getValue()) {//最近查看的
				return getMyViewList(page, paramMap);
			} else if (searchPlan == AppSearchPlanEnum.WEEKFOLLOWUP.getValue()){//一周未跟进
				//TODO一周未跟进查询
				return getMyOwnerList(page, paramMap);
			} else if (searchPlan == AppSearchPlanEnum.CREATE.getValue()) {//最近创建的
				return getMyOwnerList(page, paramMap);
			} else if (searchPlan == AppSearchPlanEnum.ASSIGNED.getValue()) {//已分配
				return getMyOwnerList(page, paramMap);
			} else if (searchPlan == AppSearchPlanEnum.UNASSIGNED.getValue()) {//未分配
				return getMyOwnerList(page, paramMap);
			}
		}
		
		//PC端根据查询方案查询客户
		paramMap = queryService.handleSearchPlan(paramMap);
		
		return getMyOwnerList(page, paramMap);
	}
	
	public Page<CustomerVO> getMyOwnerList(Page<CustomerVO> page,
			Map<String, Object> paramMap) {
		String tenantIdStr = (String) InvocationInfoProxy.getTenantid();
		Long tenantId = Long.parseLong(tenantIdStr);
		paramMap.put("tenantId", tenantId);
		Page<GroupCustomerDO> doPage = dao.pageSelect(GroupCustomerDO.class, page, "selectByGroup", "countByGroup", paramMap);
		Page<CustomerVO> pageList = ModelUtil.copyPageModel(doPage, CustomerVO.class, new IConverter<GroupCustomerDO, CustomerVO>() {
            @Override
            public void convert(GroupCustomerDO origObj, CustomerVO destObj) {
                List<CustomerSalesVO> saleVos = ModelUtil.copyModelList(origObj.getSalesDOs(), CustomerSalesVO.class);
                destObj.setSalesVOs(saleService.transCustomerSale(saleVos));
            }
        });
		transCustomer(pageList.getData());
		return pageList;
	}
	
	public Page<CustomerVO> getMyRelList(Page<CustomerVO> page, Map<String, Object> paramMap) {
		return page;
	}
	
	public Page<CustomerVO> getMyFollowList(Page<CustomerVO> page, Map<String, Object> paramMap) {
		String userIdStr = (String)InvocationInfoProxy.getParameter("id");//用户id
		String orgIdStr = (String)InvocationInfoProxy.getParameter("orgid");//所属公司
		String tenantIdStr = (String)InvocationInfoProxy.getTenantid();
		Long userId = Long.parseLong(userIdStr);
		Long orgId = Long.parseLong(orgIdStr);
		Long tenantId = Long.parseLong(tenantIdStr);
		paramMap.put("userId", userId);
		paramMap.put("orgId", orgId);
		paramMap.put("tenantId", tenantId);
		Page<GroupCustomerDO> doPage = dao.pageSelect(GroupCustomerDO.class, page, "selectByFollow", "countByFollow", paramMap);
		Page<CustomerVO> pageList = ModelUtil.copyPageModel(doPage, CustomerVO.class);
		transCustomer(pageList.getData());
		return pageList;
	}
	
	public Page<CustomerVO> getMyViewList(Page<CustomerVO> page, Map<String, Object> paramMap) {
		String userIdStr = (String)InvocationInfoProxy.getParameter("id");//用户id
		String orgIdStr = (String)InvocationInfoProxy.getParameter("orgid");//所属公司
		String tenantIdStr = (String)InvocationInfoProxy.getTenantid();
		Long userId = Long.parseLong(userIdStr);
		Long orgId = Long.parseLong(orgIdStr);
		Long tenantId = Long.parseLong(tenantIdStr);
		paramMap.put("userId", userId);
		paramMap.put("orgId", orgId);
		paramMap.put("tenantId", tenantId);
		Page<GroupCustomerDO> doPage = dao.pageSelect(GroupCustomerDO.class, page, "selectByView", "countByView", paramMap);
		Page<CustomerVO> pageList = ModelUtil.copyPageModel(doPage, CustomerVO.class);
		transCustomer(pageList.getData());
		return pageList;
	}
	
    public Map<String, Object> getViewUserList(Long cumId, Map<String, Object> paramMap) {
		String orgIdStr = (String)InvocationInfoProxy.getParameter("orgid");//所属公司
		String tenantIdStr = (String)InvocationInfoProxy.getTenantid();
		Long orgId = Long.parseLong(orgIdStr);
		Long tenantId = Long.parseLong(tenantIdStr);
		paramMap.put("orgId", orgId);
		paramMap.put("tenantId", tenantId);
		paramMap.put("cumId", cumId);
		List<Map<String, Object>> list = dao.selectList(GroupCustomerDO.class, "viewUsers", paramMap);
		Map<String, Object> rs = new HashMap<String, Object>();
		rs.put("users", list);
		return rs;
	}
	
    public Map<String, Object> getFollowUserList(Long cumId, Map<String, Object> paramMap) {
		String orgIdStr = (String)InvocationInfoProxy.getParameter("orgid");//所属公司
		String tenantIdStr = (String)InvocationInfoProxy.getTenantid();
		Long orgId = Long.parseLong(orgIdStr);
		Long tenantId = Long.parseLong(tenantIdStr);
		paramMap.put("orgId", orgId);
		paramMap.put("tenantId", tenantId);
		paramMap.put("cumId", cumId);
		List<Map<String, Object>> list = dao.selectList(GroupCustomerDO.class, "followUsers", paramMap);
		Map<String, Object> rs = new HashMap<String, Object>();
		rs.put("users", list);
		return rs;
	}
	
	public int checkNameExist(CustomerVO vo) {
		Map<String, Object> param = new HashedMap<String, Object>();
		param.put("name", vo.getName());
		Long id = vo.getId();
		param.put("id", id);
		int count = dao.countAll(GroupCustomerDO.class, "checkNameExist", param);
		if (count > 0) {
			return 1;
		}
		return 0;
	}
	
	public int delete(Long id){
		//客户是否停用
		String disableMsg = checkCustomerDisable(id);
		if(disableMsg != null){
			throw new CrmBusinessException(disableMsg);
		}
		GroupCustomerDO gDO = new GroupCustomerDO();
		gDO.setId(id);
		this.beforeDeleteVO(gDO);
		return dao.delete(gDO);
	}
	
	public int batchDelete(String[] ids) {
		Map<String, Object> param = new HashMap<String, Object>();
	    param.put("ids", ids);
		List<CustomerDO> cdos = dao.selectVoList(CustomerDO.class, "idsGetCustomer", param);
        List<String> afterCheck = new ArrayList<String>();
        for(CustomerDO cd:cdos){
        	//判断客户是否停用
            String disableMsg = checkCustomerDisable(cd.getId());
            if(disableMsg != null){
            	continue;
            }
            afterCheck.add(cd.getId().toString());
        }
        String[] stringTemp = afterCheck.toArray(new String[0]);
		
		int delNum = super.batchDeleteByIDs(GroupCustomerDO.class, stringTemp);
		saleService.batchDeleteByCumIds(stringTemp);
		viewService.batchDeleteByCumIds(stringTemp);
		return delNum;
	}
	
	public int updateState(Long id, int enableState){
		String userIdStr = (String)InvocationInfoProxy.getParameter("id");// 用户id
		Long userId = Long.parseLong(userIdStr);
		Date date = new Date();
		CustomerVO customer = new CustomerVO();
		customer.setId(id);
		customer.setEnableState(enableState);
		customer.setEnableTime(date);
		customer.setEnableUserId(userId);
		customer.setSysModifiedTime(date);
		customer.setSysModifiedUserId(userId);
		return dao.updateSql(GroupCustomerDO.class, "updateState", customer);
	}
	
	public void batchUpdateState(String[] ids, Integer enableState) {
		String userIdStr = (String) InvocationInfoProxy.getParameter("id");// 用户id
		Long userId = Long.parseLong(userIdStr);
		Date date = new Date();
		Map<String, Object> enableParaMap = new HashMap<String, Object>();
		enableParaMap.put("ids", ids);
		enableParaMap.put("enableState", enableState);
		enableParaMap.put("enableUserId", userId);
		enableParaMap.put("enableTime", date);
		enableParaMap.put("sysModifiedUserId", userId);
		enableParaMap.put("sysModifiedTime", date);
		
		 //插入动态
        if(ids != null && ids.length != 0){
        	for(String cumIdStr : ids){
        		Long cumId = Long.parseLong(cumIdStr);
        		updateStateDym(cumId, enableState);
        	}
        }
		dao.updateSql(GroupCustomerDO.class, "batchUpdateEnableState",
				enableParaMap);
	}
	
	@Override
	protected void beforeSaveVO(GroupCustomerDO gDO) {
		CustomerVO vo = ModelUtil.copyModel(gDO, CustomerVO.class);
		int exist = checkNameExist(vo);
		if (exist == 1) {
			throw new CrmBusinessException("客户名称已存在");
		}
		super.beforeSaveVO(gDO);
		String userIdStr = (String) InvocationInfoProxy.getParameter("id");// 用户id
		String orgIdStr = (String) InvocationInfoProxy.getParameter("orgid");// 所属公司
		Long userId = Long.parseLong(userIdStr);
		Long orgId = Long.parseLong(orgIdStr);
		Date date = new Date();
		gDO.setOrgId(orgId);
		gDO.setCreatedTime(date);
		gDO.setCreatedUserId(userId);
		gDO.setType(1); // 客户类型默认为：经销商
		gDO.setState(18); // 客户状态默认为：潜在客户
		gDO.setIsGroup(2); // 是否集团客户默认为：集团客户
		gDO.setEnableState(1); //启用状态默认为：启用
	}
	
	public CustomerVO saveVO(CustomerVO vo){
		GroupCustomerDO gDO = super.saveVO(ModelUtil.copyModel(vo, GroupCustomerDO.class));
		vo = ModelUtil.copyModel(gDO, CustomerVO.class);
		transCustomer(Arrays.asList(vo));
		return vo;
	}
	
	@Override
	protected void afterSaveVO(GroupCustomerDO custDo) {
		super.afterSaveVO(custDo);
		//插入动态
        UserVO user = getCurrentUser();
        Long[] relUserArr = null;
		DymGCustomerCreate cusCreate = new DymGCustomerCreate(dynamicService,user,custDo,relUserArr);
		cusCreate.execute();
		if(custDo.getLatitude() != null && !"".equals(custDo.getLatitude())
				&& custDo.getLongitude() != null && !"".equals(custDo.getLongitude())){
			DymGCumLocationSave locationCreate = new DymGCumLocationSave(dynamicService, user, custDo,relUserArr);
			locationCreate.execute();
		}
	}
	
	public CustomerVO updateVO(CustomerVO vo) {
		//客户是否停用
		String disableMsg = checkCustomerDisable(vo.getId());
		if(disableMsg != null){
			throw new CrmBusinessException(disableMsg);
		}
		
		//插入动态
		CustomerVO oriVo = getDetail(vo.getId());
		GroupCustomerDO gDO = super.updateVO(ModelUtil.copyModel(vo, GroupCustomerDO.class));
		UserVO user = getCurrentUser();
		Long[] relUserArr = handleRelUserList(vo.getId());
        if(!oriVo.getName().equals(vo.getName())){//客户名称修改
    		DymGCustomerUpdate cusUpdate = new DymGCustomerUpdate(dynamicService, user, oriVo, vo,relUserArr);
    		cusUpdate.execute();
        }
        if((oriVo.getLatitude() != null && !oriVo.getLatitude().equals(vo.getLatitude()))
        		|| (oriVo.getLongitude() != null && !oriVo.getLongitude().equals(vo.getLongitude()))){//客户位置变更
        	DymGCumLocationUpdate locationUpdate = new DymGCumLocationUpdate(dynamicService, user, vo, relUserArr);
        	locationUpdate.execute();
        }
		
		vo = ModelUtil.copyModel(gDO, CustomerVO.class);
		transCustomer(Arrays.asList(vo));
		return vo;
	}
	
	@Override
	protected void beforeUpdateVO(GroupCustomerDO gDO) {
//		CustomerVO vo = ModelUtil.copyModel(gDO, CustomerVO.class);
//		int exist = checkNameExist(vo);
//		if (exist == 1) {
//			throw new CrmBusinessException("客户名称已存在");
//		}
		super.beforeUpdateVO(gDO);
		String userIdStr = (String) InvocationInfoProxy.getParameter("id");// 用户id
		Long userId = Long.parseLong(userIdStr);
		Date date = new Date();
		gDO.setModifiedTime(date);
		gDO.setModifiedUserId(userId);
		gDO.setType(1); // 客户类型默认为：经销商
		gDO.setState(18); // 客户状态默认为：潜在客户
		gDO.setIsGroup(2); // 是否集团客户默认为：集团客户
	}
	
	@Override
	protected void afterUpdateVO(GroupCustomerDO gDO) {
		super.afterUpdateVO(gDO);
		CustomerVO	vo = ModelUtil.copyModel(gDO, CustomerVO.class);
		transCustomer(Arrays.asList(vo));
	}
	
	@Override
	protected void beforeDeleteVO(GroupCustomerDO gDO) {
		String userIdStr = (String)InvocationInfoProxy.getParameter("id");// 用户id
		Long userId = Long.parseLong(userIdStr);
		Date date = new Date();
		gDO.setDeletedTime(date);
		gDO.setDeletedUserId(userId);
		gDO.setSysModifiedTime(date);
		gDO.setSysModifiedUserId(userId);
	}
	
	@Override
	protected void afterDeleteVO(GroupCustomerDO gDO) {
		saleService.delete(gDO.getId());
	}
	
	public Object selectFieldsByIds(Object[] ids) {
		Map<String, Object> para = new HashMap<String, Object>();
		para.put("ids", ids);
		return dao.selectList(GroupCustomerDO.class, "selectFieldsByIds", para);
	}
	
    public Object selectCustomerSaleOrgById(Object[] ids) {
        Map<String, Object> para = new HashMap<String, Object>();
        para.put("ids", ids);
        return dao.selectList(GroupCustomerDO.class, "selectCustomerSaleOrgById", para);
    }
	
	private List<CustomerVO> transCustomer(List<CustomerVO> customerList) {
		List<FieldRelation<CustomerVO>> relations = new ArrayList<FieldRelation<CustomerVO>>();
		relations.add(new RefFieldRelation<CustomerVO>(CustomerVO.class, "id", new String[]{"orgNames"}, this, "selectCustomerSaleOrgById"));
		//业务类型
        relations.add(new RefFieldRelation<CustomerVO>(CustomerVO.class, "biztypeId", new String[]{"biztypeName"}, biztypeService, "selectFieldsByIds"));
		//基础档案：1-客户类型、2-渠道类型、5-客户等级、6-客户状态
		relations.add(new RefFieldRelation<CustomerVO>(CustomerVO.class, "type", new String[]{"typeName"}, baseDocDetailBizService, "selectFieldsByIds"));
		relations.add(new RefFieldRelation<CustomerVO>(CustomerVO.class, "cannelType", new String[]{"cannelTypeName"}, baseDocDetailBizService, "selectFieldsByIds"));
		relations.add(new RefFieldRelation<CustomerVO>(CustomerVO.class, "level", new String[]{"levelName"}, baseDocDetailBizService, "selectFieldsByIds"));
		relations.add(new RefFieldRelation<CustomerVO>(CustomerVO.class, "state", new String[]{"stateName"}, baseDocDetailBizService, "selectFieldsByIds"));
		//行业
		relations.add(new RefFieldRelation<CustomerVO>(CustomerVO.class, "industry", new String[]{"industryName"}, IndustryBizService, "selectFieldsByIds"));
		//上级客户
		relations.add(new RefFieldRelation<CustomerVO>(CustomerVO.class, "parentId", new String[]{"parentName"}, this, "selectFieldsByIds"));
		//省、市、区
		relations.add(new RefFieldRelation<CustomerVO>(CustomerVO.class, "province", new String[]{"provinceName"}, regionService, "selectFieldsByIds"));
		relations.add(new RefFieldRelation<CustomerVO>(CustomerVO.class, "city", new String[]{"cityName"}, regionService, "selectFieldsByIds"));
		relations.add(new RefFieldRelation<CustomerVO>(CustomerVO.class, "district", new String[]{"districtName"}, regionService, "selectFieldsByIds"));
		//启用标识
		relations.add(new EnumFieldRelation<CustomerVO>(CustomerVO.class, "enableState", "enableStateName", enumService, "enable_state"));
		//集团客户标识
		relations.add(new EnumFieldRelation<CustomerVO>(CustomerVO.class, "isGroup", "isGroupName", enumService, "cum_sign"));
		new FieldRelationHandler<CustomerVO>().handler(customerList, relations);
		return customerList;
	}
	
	public List<ReferDataVO> getRefervalues(Page<CustomerVO> page, Map<String, Object> paraMap) {
		// TODO 加权限
		Page<GroupCustomerDO> pageVO = dao.pageSelect(GroupCustomerDO.class, page, "selectRefervalues", "countRefervalues", paraMap);
		List<GroupCustomerDO> voList = pageVO.getData();
		
		List<ReferDataVO> rsList = new ArrayList<ReferDataVO>();
		for (GroupCustomerDO vo : voList) {
			ReferDataVO referDataVO = new ReferDataVO();
			referDataVO.setId(vo.getId().toString());
			referDataVO.setValue(vo.getName());
			rsList.add(referDataVO);
		}
		return rsList;
	}
	
	public List<CustomerVO> getRefervaluesForApp(Page<CustomerVO> page, Map<String, Object> paraMap) {
		// TODO 加权限
		Page<GroupCustomerDO> doPage = dao.pageSelect(GroupCustomerDO.class, page, "selectRefervalues", "countRefervalues", paraMap);

		Page<CustomerVO> voPage = ModelUtil.copyPageModel(doPage, CustomerVO.class);
		List<CustomerVO> voList = voPage.getData();
		return voList;
	}
	
	//参照列表
	public List<CustomerVO> getRefList(Map<String, Object> paraMap) {
		if (paraMap == null) {
			paraMap = new HashMap<String, Object>();
		}
		paraMap.put("tenantId", new Long(InvocationInfoProxy.getTenantid()));
		List<GroupCustomerDO> doList = dao.selectVoList(GroupCustomerDO.class, "getRefList", paraMap);
		List<CustomerVO> voList = ModelUtil.copyModelList(doList, CustomerVO.class);
		return voList;
	}
	
	//分页参照列表
	public Page<CustomerVO> getRefPage(Page<CustomerVO> page, Map<String, Object> paraMap) {
		if (paraMap == null) {
			paraMap = new HashMap<String, Object>();
		}
		paraMap.put("tenantId", new Long(InvocationInfoProxy.getTenantid()));
		Page<GroupCustomerDO> doPage = dao.pageSelect(GroupCustomerDO.class, page, "getRefPage", "countRefPage", paraMap);
		Page<CustomerVO> voPage = ModelUtil.copyPageModel(doPage, CustomerVO.class);
		transCustomer(voPage.getData());
		return voPage;
	}
	
    /**
     * 判断公司是否已被核实
     * @param paraMap
     * @return
     */
	public boolean getIdentifyFlag(Map<String, Object> paraMap){
		boolean flag = false;
		GroupCustomerDO customer = (GroupCustomerDO) dao.selectOne(GroupCustomerDO.class, "selectVOByVerifyId", paraMap);
		if (customer != null) {
			throw new CrmBusinessException("该公司已被"+customer.getName()+"客户认证");
		}
		return flag;
	}
	
    /**
     * 根据verifyId判断是否已被核实
     * @param vo
     */
	public void checkVerifyIdExist(CustomerVO vo){
		Map<String, Object> param = new HashedMap<String, Object>();
		param.put("verifyId", vo.getVerifyId());
		Long id = vo.getId();
		param.put("id", id);
		GroupCustomerDO customer = (GroupCustomerDO) dao.selectOne(GroupCustomerDO.class, "selectVOByVerifyId", param);
		if (customer != null) {
			throw new CrmBusinessException("该公司已被"+customer.getName()+"客户认证");
		}
	}
	
    /**
     * 根据verifyFullname判断是否已被核实
     * @param id
     * @param verifyName
     * @return
     */
	public boolean checkVerifyNameExist(String id, String verifyName){
		Map<String, Object> param = new HashedMap<String, Object>();
		param.put("verifyFullname", verifyName);
		param.put("id", id);
		GroupCustomerDO customer = (GroupCustomerDO) dao.selectOne(GroupCustomerDO.class, "selectVOByVerifyName", param);
		if (customer != null) {
			return true;
		}
		return false;
	}
	
    /**
     * 企业核实
     * @param vo
     * @return
     */
	public CustomerVO identify(CustomerVO vo) {
		checkVerifyIdExist(vo);
		GroupCustomerDO gDO = ModelUtil.copyModel(vo, GroupCustomerDO.class);
		dao.update(gDO);
		vo = ModelUtil.copyModel(gDO, CustomerVO.class);
        transCustomer(Arrays.asList(vo));
		return vo;
	}
	
    /**
     * 取消核实
     * @param vo
     * @return
     */
	public CustomerVO cancelIdentify(CustomerVO vo){
		GroupCustomerDO gDO = ModelUtil.copyModel(vo, GroupCustomerDO.class);
		dao.update(gDO);
		vo = ModelUtil.copyModel(gDO, CustomerVO.class);
		transCustomer(Arrays.asList(vo));
		return vo;
	}
	
	/**
	 * 获取集团客户动态
	 * @param cumId
	 * @return
	 */
	public DynamicVO[] getCumDynamic(Long cumId) {
		Long curUser = Long.parseLong(InvocationInfoProxy.getParameter(LoginContextConstant.UserId));
		DynamicVO[] dyms = dynamicService.getBusiDynamic((long)ObjTypeEnum.CUSTOMER_G.getValue(), cumId);
		CustomerVO customer = getDetail(cumId);
		Field bFromField = new Field("",new Link("","CUSTOMER",cumId,"",""));
		Field bToField = new Field("该",new Link("客户","CUSTOMER",cumId,"",""));
		BusiFilter busiFilter = new BusiFilter(bFromField,bToField);
		MyFilter myFilter = new MyFilter(curUser,"我");
		DateTimeFilter dtFilter = new DateTimeFilter(System.currentTimeMillis());
		for(int i=0,len=dyms.length;i<len;i++) {
			busiFilter.doFilter(dyms[i]);
			myFilter.doFilter(dyms[i]);
			dtFilter.doFilter(dyms[i]);
		}
		return dyms;
	}
	
	/**
	 * 查询客户是否停用
	 * @param cumId
	 * @return
	 */
	private String checkCustomerDisable(Long cumId) {
		CustomerVO customer = getDetail(cumId);
		if(customer.getEnableState() == 2){
			return "该客户已停用";
		}
		return null;
	}
	
	/**
	 * 获取当前登录用户
	 * @return
	 */
	public UserVO getCurrentUser(){
		Long curUser = Long.parseLong(InvocationInfoProxy.getParameter(LoginContextConstant.UserId));
		UserVO user = userService.getDetail(curUser);
		return user;
	}
	
	public Long[] handleRelUserList(Long cumId){
		String orgIdStr = InvocationInfoProxy.getParameter(LoginContextConstant.OrgId);
		Long orgId = Long.parseLong(orgIdStr);
		Long[] idArr = new Long[]{};
		List<Long> idList = new ArrayList<Long>();
		//查询公司客户负责人，添加到dynamic_follow表中
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("cumId", cumId);
		param.put("tenantId", InvocationInfoProxy.getTenantid());
		List<CustomerSalesVO> salesList = saleService.selectByCustomer(param);
		if(salesList != null && salesList.size() > 0){
			for(CustomerSalesVO cumSale : salesList){
				if(cumSale.getOrgId().equals(orgId)){
					idList.add(cumSale.getOwnerUserId());
				}
			}
		}
		//查询客户参与人，添加到dynamic_follow表中
		List<CustomerRelusersVO> refuserList = cusreluserService.getCumRelusers(cumId);
		if(refuserList != null && refuserList.size() > 0){
			for(CustomerRelusersVO relUser : refuserList){
				idList.add(relUser.getUserId());
			}
			if(idList != null && idList.size() > 0){
				idArr = idList.toArray(new Long[0]);
			}
		}
		return idArr;
	}
	
	/**
     * 停启用生成动态
     * @param id
     * @param enableState
     */
    private void updateStateDym(Long id, int enableState){
    	UserVO user = getCurrentUser();
		Long[] relUserArr = handleRelUserList(id);
		CustomerVO vo = getDetail(id);
        switch (enableState) {
        case 1:
        	DymGCumEnable cumEnable = new DymGCumEnable(dynamicService, user, vo, relUserArr);
        	cumEnable.execute();
        	break;
        case 2:
        	DymGCumDisable cumDisable = new DymGCumDisable(dynamicService, user, vo, relUserArr);
        	cumDisable.execute();
        	break;
        default:
        	break;
        }
    }
	
}
